<?php
namespace Admin\Controller;
use Admin\Controller\CommonController;

/**
 * 小说
*/
class SubjectController extends CommonController {
    protected $db;
    function __construct() {
        parent::__construct();
        $this->db = D("Subject");
    }

    public function index() {
        $lists = $this->db->subject_list();
        $this->assign('lists',$lists);
        $this->display();
    }

    public function delete() {
        if (IS_POST) {
            $ids = $_POST['ids'];
            if (!empty($ids) && is_array($ids)) {
                if ($this->db->delete_subject($ids)) {
                    $this->success('删除成功！');
                } else {
                    $this->error('删除失败！');
                }
            } else {
                $this->error("您没有勾选信息");
            }
        } else {
            if ($this->db->delete_subject(intval($_GET['id']))) {
                $this->success('删除成功！');
            } else {
                $this->error('删除失败！');
            }
        }
    }

    public function add(){
        if (IS_POST) {
            $nid = I('nid');
            $subject = I('subject');
            $subjects = explode(',', $subject);

            $res = D('SubjectNovelIdx')->where(array('nid' => $nid))->delete();
            if($res !== false){
                foreach($subjects as $sid){
                    $data = array(
                        'nid' => $nid,
                        'sid' => trim($sid),
                    );
                    D('SubjectNovelIdx')->add($data);
                }
            }
            $this->ajaxReturn(1);
        } else {
            $novels = D('Novel')->novel_list();
            foreach($novels as $key=>$novel){
                $subjects = D('SubjectNovelIdx')->where(array('nid' => $novel['id']))->select();
                $sid = array();
                foreach($subjects as $subject){
                    $sid[] = $subject['sid'];
                }
                $novels[$key]['subjects'] = implode(',', $sid);
            }
            $this->assign('novels',$novels);
            $this->display();
        }
    }

}